package bch.rocketmq.netty;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Properties;


/**
 * @author DCJ
 * <p>
 * Raw  -- ws://192.168.1.87:2469/ws
 */
@Component
@Slf4j
public class WebSocketServer implements CommandLineRunner {

    @Value("${server.port:2369}")
    private int port;

    @Resource
    private WebSocketServerChannelInitializer webSocketServerChannelInitializer;

    public void init() throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap

                    // 指定单线程 多线程 主从架构
                    .group(bossGroup, workerGroup)
                    // 隐式添加了acceptor
                    .handler(new LoggingHandler(LogLevel.WARN))

                    .channel(NioServerSocketChannel.class)

                    .childHandler(webSocketServerChannelInitializer);

            // 同步等待异步请求的结果, 等待bind结果
            ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(port + 100)).sync();

            // 同步等待channel关闭
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }


    @Override
    public void run(String... args) throws Exception {
        init();
    }
}